﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace CPlase
{
    public static class LinqExtension
    {
        public static Expression<Func<T, bool>> Contains<T>(string ObjectStringName, string FieldStringNameToCompare, IList<String> ListOfValues)
        {
            Expression ExprBody = null;
            ParameterExpression ParameterObject = Expression.Parameter(typeof(T), ObjectStringName);
            var PropertyFieldToCompare = Expression.Property(ParameterObject, FieldStringNameToCompare);
            foreach (var ValueToCompare in ListOfValues)
            {
                ConstantExpression ValueConst = Expression.Constant(ValueToCompare, typeof(string));
                BinaryExpression EqualTermExpression = Expression.Equal(PropertyFieldToCompare, ValueConst);
                if (ExprBody == null) { ExprBody = EqualTermExpression; }
                else
                {
                    ExprBody = Expression.Or(ExprBody, EqualTermExpression);
                }
            }
            if (ExprBody == null)
            {
                ExprBody = Expression.IsTrue(Expression.Constant(false));
            }
            var FinalExpression = Expression.Lambda<Func<T, bool>>(ExprBody, new ParameterExpression[] { ParameterObject });

            return FinalExpression;
        }

        public static IQueryable<T> Contains<T>(this IQueryable<T> obj, string ObjectStringName, string FieldStringNameToCompare, IList<String> ListOfValues)
        {
            var Expression = Contains<T>(ObjectStringName, FieldStringNameToCompare, ListOfValues);
            if (Expression != null)
                return obj.Where<T>(Expression);
            return obj;
        }
    }
}